import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Image, Text, Block, Canvas, Button } from '@tarojs/components';
import { sysInfo } from '@/utils/utils';
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"

import './index.scss';

type Props = {
  isHide: () => void,
  showType: string
};
type State = {
  moreBtn: boolean,
  list: any[],
  width: number,
  height: number,
  isModal: boolean
}
// 
class PropertyPlaybill extends Component<Props, State> {
  readonly state: State = {
    moreBtn: false,
    list: [],
    height: 0,
    width: 0,
    isModal: false,
  }
  static defaultProps = {
    data: []
  }
  ctx: any
  canvas: any
  imageUrl: string[] = [
    'https://f3-md.veimg.cn/meadinjuWX/img/dealcard.jpg',
    'https://f3-md.veimg.cn/meadinjuWX/img/success-icon.png',
    'https://f3-md.veimg.cn/meadinjuWX/img/bill-logo.png', 
  ];
  imgList: string[] = [];
  $instance: any = Taro.getCurrentInstance()
  tempFilePath: string
  UNSAFE_componentWillMount() {
    // const events = new Taro.eventCenter();
    Taro.eventCenter.on(this.$instance.router.onReady, () => {
      this.initCanvas();
    })
  }
  componentDidMount() {
    const scale = sysInfo.windowWidth / 750;
    // const scale = sysInfo.devicePixelRatio;
    if (this.props.showType === 'brand') {
      this.setState({
        width: scale * 710,
        height: scale * 702
      })
    }
    if (this.props.showType === 'plain') {
      this.setState({
        width: scale * 710,
        height: scale * 832
      })
    }
  }
  componentWillUnmount() {
    // 卸载
    Taro.eventCenter.off(this.$instance.router.onReady)
  }
  downloadImage = (imgUrl) => {
    return new Promise((resolve, reject) => {
      Taro.getImageInfo({
        src: imgUrl,
        success: (res) => {
          const getImg = this.canvas.createImage()
          getImg.src = res.path;
          getImg.onload = () => {
            resolve(getImg)
          }
        },
        fail: () => {
          Taro.showToast({
            title: '下载失败!'
          })
        }
      })
    })
    
  }
  initCanvas = async () => {
    //初始化canvas
    let canvasNode: any = await new Promise((resolve, reject) => {
      const query = Taro.createSelectorQuery()
      query.select('#canvasBill').fields({ node: true, size: true }).exec(res => {
        resolve(res[0])
      })
    })
    this.canvas = canvasNode.node;
    await Promise.all(this.imageUrl.map( img => this.downloadImage(img))).then((res) => {
      // return res.map((i: any) => i.path);
      return res.map((i: any) => i);
    }).then(res => {
      this.imgList = res;
    })
    if (!this.ctx) {
      this.ctx = this.canvas.getContext('2d');
      // 资产交易、租赁、投融资
      this.props.showType === 'plain' && this.assetDrawImage();
      this.props.showType === 'brand' && this.brandDrawImage();
    }
  }
  // 资产交易、租赁、投融资
  assetDrawImage = () => {
    const scale = sysInfo.devicePixelRatio;
    const ctx  = this.ctx;
    const imgList = this.imgList;
    const isTitle = '杭州未来科技城板块精品酒店出售';
    this.canvas.width = scale * 710;
    this.canvas.height = scale * 832;
    // 436
    ctx.save()
    this.roundRect(ctx, 0, 0, scale * 710, scale * 832, scale * 16 )
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, scale * 436, scale * 710, scale * 396);
    // 海报
    ctx.drawImage(imgList[0], 0, 0, scale * 710, scale * 436);
    // // 迈居logo
    ctx.drawImage(imgList[2], scale * 31, scale * 764, scale * 78, scale * 26);
    // 标题
    ctx.fillStyle = '#333333';
    ctx.textBaseline = 'top'
    ctx.font = `normal normal bold  ${scale * 38}px sans-serif`;
    ctx.fillText(isTitle, scale * 31, scale * 466 );
    ctx.font = `normal normal bold  ${scale * 26}px sans-serif`;
    ctx.fillText('长按识别小程序码', scale * 31, scale * 645 );
    ctx.fillStyle = '#65676F';
    ctx.fillText('进入【迈居】小程序查看项目详情', scale * 31, scale * 686 );
    ctx.font = `normal normal normal  ${scale * 20}px sans-serif`;
    ctx.fillStyle = '#8C8C8C';
    ctx.fillText('商业空间资产交易与品牌加盟信息服务平台', scale * 116, scale * 766 );
    // 内容
    ctx.fillStyle = '#FFA409'
    ctx.font = `normal normal bold  ${scale * 30}px sans-serif`;
    ctx.fillText('2500万', scale * 31, scale * 537 );
    ctx.fillText('杭州', scale * 216, scale * 537 );
    ctx.fillText('经营中', scale * 359, scale * 537 );
    // // 线条
    ctx.beginPath()
    ctx.strokeStyle = 'rgba(116, 131, 167, 0.05)';
    ctx.lineWidth = scale * 3
    ctx.moveTo(scale * 186, scale * 541)
    ctx.lineTo(scale * 186, scale * 571)
    ctx.moveTo(scale * 326, scale * 541)
    ctx.lineTo(scale * 326, scale * 571)
    ctx.stroke()
    // 小程序二维码
    ctx.beginPath()
    ctx.strokeStyle = '#FFA409';
    ctx.arc(scale * 576, scale * 704, 85 * scale, 0, 2*Math.PI)
    ctx.lineWidth = scale * 2
    ctx.clip()
    ctx.drawImage(imgList[1], scale * 491, scale * 619, scale * 170, scale * 170);
    ctx.stroke()
  }
  brandDrawImage = () => {
    const scale = sysInfo.devicePixelRatio;
    const imgList = this.imgList;
    const isTitle = '杭州未来科技城板块精品酒店出售';
    // 迈居logo
    const ctx = this.ctx;
    // ctx.translate(0, 0);
    this.canvas.width = scale * 710;
    this.canvas.height = scale * 702;
    ctx.save()
    this.roundRect(ctx, 0, 0, scale * 710, scale * 702, scale * 16 )
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, scale * 710, scale * 702)
    ctx.fill()
    // 海报
    let bj = 61;
    let tm = 1;
    for (let i = 0; i < 9; i++) {
      bj = bj + 15;
      i > 0 && i%3 === 0 && (tm = tm - 0.3);
      ctx.beginPath()
      
      ctx.strokeStyle = `rgba(235, 235, 235, ${tm})`;
      ctx.arc(scale * 106, scale * 116, scale * bj, 0, 2*Math.PI)
      ctx.stroke()
    }
    ctx.beginPath()
    
    ctx.strokeStyle = '#A6A9AC'
    ctx.arc(scale * 106, scale * 116, scale * 76, 0, 2*Math.PI)
    ctx.stroke()
    ctx.clip()
    ctx.drawImage(imgList[0], scale * 30, scale * 40, scale * 152, scale * 152);
    ctx.restore()
    ctx.arc(scale * 106, scale * 116, scale * 76, 0, 2*Math.PI)
    // // 内容
    ctx.textBaseline = 'top'
    ctx.fillStyle = '#333333';
    ctx.font = `normal normal bold  ${scale * 40}px sans-serif`;
    ctx.fillText('维也纳', scale * 222,  scale * 47)
    ctx.font = `normal normal bold  ${scale * 30}px sans-serif`;
    ctx.fillText('加盟优势：', scale * 36,  scale * 296)
    ctx.fillText('资本直投，品牌加持；丰富的流量支持渠道。', scale * 36,  scale * 341)


    ctx.fillStyle = '#A6A9AC';
    ctx.font = `normal normal normal  ${scale * 24}px sans-serif`;
    ctx.fillText('有限服务中档酒店', scale * 222, scale * 109 );
    ctx.fillText('单房造价: ', scale * 222, scale * 150 );
    ctx.fillText('面积要求: ', scale * 222, scale * 183 );
    ctx.fillStyle = "#444444";
    ctx.fillText('10-13万', scale * 332, scale * 150 );
    ctx.fillText('5000-8000㎡', scale * 332, scale * 183 );


    ctx.drawImage(imgList[2], scale * 31, scale * 634, scale * 78, scale * 26);
    ctx.fillStyle = "#333333";
    ctx.font = `normal normal bold  ${scale * 28}px sans-serif`;
    ctx.fillText('长按识别小程序码', scale * 31, scale * 515 );
    ctx.font = `normal normal normal  ${scale * 26}px sans-serif`;
    ctx.fillText('进入【迈居】小程序查看项目详情', scale * 31, scale * 556 );
    ctx.font = `normal normal normal  ${scale * 20}px sans-serif`;
    ctx.fillStyle = '#8C8C8C';
    ctx.fillText('商业空间资产交易与品牌加盟信息服务平台', scale * 116, scale * 636 );
    // // 小程序二维码
    ctx.beginPath()
    
    ctx.strokeStyle = '#FFA409'
    ctx.arc(scale * 576, scale * 574, 85 * scale, 0, 2*Math.PI)
    ctx.globalCompositeOperation="source-over";
    ctx.lineWidth = scale * 2
    ctx.clip()
    ctx.drawImage(imgList[1], scale * 491, scale * 489, scale * 170, scale * 170);
    ctx.stroke()
  }
  /**
  * @param {any} ctx canvas上下文
  * @param {string} text 文字内容
  * @param {number} scale 尺寸倍率
  * @param {number} x 横坐标
  * @param {number} y 纵坐标
  */
  myFontBold = (ctx, text, scale, x, y) => {
    // ctx.font('normal bold 18px sans-serif')
    // ctx.fillText(text, scale * x, scale * y - 0.5);
    // ctx.fillText(text, scale * x - 0.5, scale * y);
    ctx.fillText(text, scale * x, scale * y);
    // ctx.fillText(text, scale * x, scale * y + 0.5);
    // ctx.fillText(text, scale * x + 0.5, scale * y);
  }
  /**
  * @param {any} ctx canvas上下文
  * @param {number} x 圆角矩形选区的左上角 x坐标
  * @param {number} y 圆角矩形选区的左上角 y坐标
  * @param {number} w 圆角矩形选区的宽度
  * @param {number} h 圆角矩形选区的高度
  * @param {number} r 圆角的半径
  */
  roundRect = (ctx, x, y, w, h, r) => {
    // 开始绘制
    ctx.beginPath()
    // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
    // 这里是使用 fill 还是 stroke都可以，二选一即可
    ctx.fillStyle = 'transparent'
    // ctx.strokeStyle('transparent')
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
  
    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
  
    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
  
    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
  
    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)
  
    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.fill()
    // ctx.stroke()
    ctx.closePath()
    // 剪切
    ctx.clip()
  }
  onClickSave = async () => {
    await Taro.canvasToTempFilePath({
      canvas: this.canvas,
      // quality: 1,
      // destWidth: this.state.width,
      // destHeight: this.state.height,
      fileType: 'png',
      success: (res) => {
        this.tempFilePath = res.tempFilePath;
      },
      fail: (err) => {
        Taro.showToast('图片生成失败！')
      }
    })
    // openSetting
    new Promise((resolve, reject) => {
      Taro.getSetting({
        success: (res) => {
          
          resolve(res)
        }
      })
    }).then((isSet: any) => {
      if (!isSet.authSetting['scope.writePhotosAlbum']) {
         Taro.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              this.saveImage()
            },
            fail: () => {
              this.setState({
                isModal: true
              })
            }
         })
      } else {
        this.saveImage()
      }
    })
  }
  saveImage = () => {
    Taro.saveImageToPhotosAlbum({
      filePath: this.tempFilePath,
      success: () => {
        this.props.isHide()
        Taro.showToast({
          title: '保存成功!'
        })
      },
      fail: () => {
        Taro.showToast({
          title: '保存失败!',
          duration: 2000
        })
      }
    })
  }
  handleCancel = () => {
    this.setState({
      isModal:  false
    })
  }
  handleConfirm = () => {
    Taro.openSetting({
      success: (res) => {
        res.authSetting['scope.writePhotosAlbum'] && this.saveImage()
      }
    })
    this.setState({
      isModal:  false
    })
  }
  render() {
    const { width, height, isModal} = this.state;
    return (
      <>
        <AtModal 
          isOpened={isModal} 
        >
          <AtModalHeader>微信授权</AtModalHeader>
          <View className="modal-con">
            保存图片或视频到你的相册
          </View>
          <AtModalAction> 
            <Button onClick={this.handleCancel}>取消</Button>
            <Button onClick={this.handleConfirm}>确定</Button>
          </AtModalAction>
        </AtModal>
        <View className="bill-canvas" catchMove={true}>
          <View className="box-c">
            <Canvas type="2d" className="is-canvas" id="canvasBill" disableScroll={true} style={{width, height}} />
          </View>
          <View className="down-cancel">
            <Button className="dowm-bill" onClick={this.onClickSave}>
              <Image src={`${_IMG_URL}/bill-down.png`}></Image>
              <View>保存</View>
            </Button>
            <Button className="cencel" onClick={() => {this.props.isHide()}}>取消</Button>
          </View>
        </View>
      </>
      
    );
  }
}
export default PropertyPlaybill;